import random
import uuid
import datetime
from io import BytesIO
from django.shortcuts import render, HttpResponse, redirect
from django.db.models import Q
from django.http import JsonResponse
from django_redis import get_redis_connection
from web.forms import account
from web import models
from utils.code import check_code

"""
用户相关的操作
"""

# """用户注册"""
def register(request):
    if request.method == "GET":
        form = account.RegisterModelForm(request)
        return render(request, 'register.html', {"form": form})
    form = account.RegisterModelForm(request, data=request.POST)
    if form.is_valid():
        print("验证通过")
        # '''验证通过'''
        instance = form.save()
        # 创建交易记录
        if instance:
            price = models.Price.objects.filter(category=1, title="个人免费版").first()
            models.OrderInfo.objects.create(
                status=2,
                order_num = str(uuid.uuid4()),
                create_user = instance,
                price = price,
                amount = 0,
                payment = 0,
                start_time = datetime.datetime.now(),
                end_time = "2099-12-30 23:59:59",
            )
        return JsonResponse({'status': True, 'url': '9999'})
        # return redirect("/home/")
    # '''验证不通过'''
    return JsonResponse({'status': False, 'error': form.errors})

# """账号密码登录"""
def login(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    print("*********用户登录请求：", ip,request.COOKIES)
    if request.method == "GET":
        form = account.LoginForm(request)
        return render(request, 'login.html', {'form': form})
    form = account.LoginForm(request, data=request.POST)
    # '''拿到用户输入的验证码'''
    # txt_code = form.cleaned_data.pop("code")
    if form.is_valid():
        user_name = form.cleaned_data['user_name']
        password = form.cleaned_data['password']
        user_obj = models.UserInfo.objects.filter(Q(user_name=user_name) | Q(email=user_name) | Q(mobile_phone=user_name), Q(password=password)).first()
        # row_object = UserInfo.objects.filter(**form.cleaned_data).first()
        if user_obj:
            # 登录成功后将账号信息写入session中
            # request.session['user_id'] = user_obj.id
            # request.session['user_name'] = user_obj.user_name
            request.session["info"] = {"user_id": user_obj.id, "user_name": user_obj.user_name,"user_email": user_obj.email}
            # 设置session过期时间 7天
            request.session.set_expiry(60 * 60 * 24 * 7)
            return JsonResponse({'status': True, 'data': '/home/'})
        form.errors['password'] = '用户名或密码错误！'
        return JsonResponse({'status': False, 'errors': form.errors})
    return JsonResponse({'status': False, 'errors': form.errors})

# """获取手机短信"""
def send_sms(request):
    conn = get_redis_connection('sms_code')
    form = account.SendSmsForm(request, data=request.GET)
    if form.is_valid():
        mobile_phone = form.cleaned_data['mobile_phone']
        sms = random.randrange(1000, 9999)
        # 把短信验证码写入到redis中，并设置60秒过期
        conn.set(mobile_phone, sms, ex=60)
        return JsonResponse({'status': True, 'sms': sms})
    else:
        return JsonResponse({'status': False, 'errors': form.errors})

# """手机短信验证码登录"""
def login_sms(request):
    if request.method == "GET":
        form = account.LoginSmsForm()
        return render(request, 'login_sms.html', {'form': form})
    form = account.LoginSmsForm(data=request.POST)
    if form.is_valid():
        user_obj = form.cleaned_data['mobile_phone']
        request.session["info"] = {"user_id": user_obj.id, "user_name": user_obj.user_name,"user_email": user_obj.email}
        # 设置session过期时间 7天
        request.session.set_expiry(60 * 60 * 24 * 7)
        data = "/home/"
        return JsonResponse({'status': True, 'data': data})
    return JsonResponse({'status': False, 'errors': form.errors})


# '''生成登录验证码'''
def img_check_code(request):
    img, img_str = check_code()
    print(img_str)
    # '''将验证码写入session，并设置60秒过期，过期后通过request.session.get("code")为None'''
    request.session["code"] = img_str
    request.session.set_expiry(60)
    # 创建一个内存空间
    stream = BytesIO()
    # 将生成的图片验证码保存在内存空间中
    img.save(stream, 'png')
    # 将从内存空间获取的图片验证码传给前端
    return HttpResponse(stream.getvalue())

def login_out(request):
    request.session.clear()
    return redirect("/home/")
